<!-- 角色扮演聊天页面 -->
<template>
  <div class="character-chat-container">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="buttons">
        <!-- 返回普通聊天按钮 -->
        <button class="back-btn" @click="goBack">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
        <!-- 创建新角色按钮 -->
        <button class="new-character-btn" @click="showCreateCharacterDialog">
          <i class="fas fa-plus"></i> 创建角色
        </button>
      </div>

      <!-- 角色列表 -->
      <div class="character-list">
        <div class="list-title">角色列表</div>
        <div v-for="character in characters" 
             :key="character.characterId" 
             :class="['character-item', { active: currentCharacter?.characterId === character.characterId }]"
             @click="selectCharacter(character)">
          <div class="character-name">{{ character.name }}</div>
          <div class="character-desc">{{ character.personality || '暂无描述' }}</div>
          <el-button
            class="delete-btn"
            type="danger"
            size="small"
            circle
            @click.stop="confirmDeleteCharacter(character)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 历史对话列表 -->
      <div v-if="currentCharacter" class="conversation-list">
        <div class="list-title">历史对话</div>
        <div v-for="conversation in conversations" 
             :key="conversation.characterConversationId" 
             :class="['conversation-item', { active: currentConversation?.characterConversationId === conversation.characterConversationId }]"
             @click="switchConversation(conversation)">
          <div class="conversation-title">{{ conversation.title }}</div>
          <el-button
            class="delete-btn"
            type="danger"
            size="small"
            circle
            @click.stop="confirmDelete(conversation)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-content">
      <template v-if="currentCharacter">
        <!-- 当前角色信息 -->
        <div class="character-info">
          <h2>{{ currentCharacter.name }}</h2>
          <p>{{ currentCharacter.description }}</p>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageList">
<<<<<<< HEAD
          <div v-for="(message, idx) in currentMessages" 
               :key="message.characterMessageId || message.id || idx" 
               :class="['message', message.senderType]">
            <div class="message-content">
              {{ message.content }}
              <audio
                v-if="message.audioUrl"
                :src="message.audioUrl"
                controls
                style="margin-top: 8px; width: 220px;"
              >
                您的浏览器不支持 audio 元素。
              </audio>
            </div>
=======
          <div v-for="message in currentMessages" 
               :key="message.id" 
               :class="['message', message.senderType]">
            <div class="message-content">{{ message.content }}</div>
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <textarea 
            v-model="inputMessage" 
            @keyup.enter.exact="sendMessage"
            placeholder="与角色对话..."
            rows="3"
          ></textarea>
          <button class="send-btn" @click="sendMessage">发送</button>
        </div>
      </template>

      <!-- 未选择角色时的提示 -->
      <div v-else class="no-character">
        <div class="prompt">
          <i class="fas fa-user-circle"></i>
          <p>请选择一个角色开始对话</p>
          <button class="create-btn" @click="showCreateCharacterDialog">
            创建新角色
          </button>
        </div>
      </div>
    </div>

    <!-- 创建角色对话框 -->
    <div v-if="showDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog" @click.stop>
        <h2>创建新角色</h2>
        <div class="form-group">
          <label>角色名称</label>
          <input v-model="newCharacter.name" placeholder="输入角色名称">
        </div>
        <div class="form-group">
          <label>年龄</label>
          <input v-model="newCharacter.age" type="number" placeholder="输入角色年龄">
        </div>
        <div class="form-group">
          <label>性格特点</label>
          <textarea 
            v-model="newCharacter.personality" 
            placeholder="描述这个角色的性格特点..."
            rows="2"
          ></textarea>
        </div>
        <div class="form-group">
          <label>职业</label>
          <input v-model="newCharacter.occupation" placeholder="输入角色职业">
        </div>
        <div class="form-group">
          <label>背景故事</label>
          <textarea 
            v-model="newCharacter.background" 
            placeholder="描述这个角色的背景故事..."
            rows="3"
          ></textarea>
        </div>
        <div class="form-group">
          <label>语言风格</label>
          <textarea 
            v-model="newCharacter.languageStyle" 
            placeholder="描述这个角色说话的风格特点..."
            rows="2"
          ></textarea>
        </div>
<<<<<<< HEAD
        <div class="form-group">
          <label>语音音色</label>
          <select v-model="newCharacter.voiceId">
            <option value="chelsie">Chelsie（女）</option>
            <option value="cherry">Cherry（女）</option>
            <option value="ethan">Ethan（男）</option>
            <option value="serena">Serena（女）</option>
            <option value="dylan">Dylan（北京话-男）</option>
            <option value="jada">Jada（吴语-女）</option>
            <option value="sunny">Sunny（四川话-女）</option>
          </select>
        </div>
        <div class="form-group">
          <label>语音参数（可选，JSON格式）</label>
          <input v-model="newCharacter.voiceSettings" placeholder='{"speed":1.0,"emotion":"happy"}'>
        </div>
=======
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426
        <div class="dialog-buttons">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="createCharacter">创建</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import axios from 'axios';

export default {
  name: 'CharacterChat',
  components: {
    Delete
  },
  setup() {
    const router = useRouter();
    const characters = ref([]);
    const currentCharacter = ref(null);
    const currentConversation = ref(null);
    const conversations = ref([]);
    const currentMessages = ref([]);
    const inputMessage = ref('');
    const messageList = ref(null);
    const showDialog = ref(false);
    const newCharacter = ref({
      name: '',
      age: null,
      personality: '',
      occupation: '',
      background: '',
<<<<<<< HEAD
      languageStyle: '',
      voiceId: 'zhitian_emo',
      voiceSettings: ''
=======
      languageStyle: ''
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426
    });

    // 返回普通聊天
    const goBack = () => {
      router.push('/chat');
    };

    // 显示创建角色对话框
    const showCreateCharacterDialog = () => {
      showDialog.value = true;
    };

    // 关闭对话框
    const closeDialog = () => {
      showDialog.value = false;
      newCharacter.value = {
        name: '',
        age: null,
        personality: '',
        occupation: '',
        background: '',
<<<<<<< HEAD
        languageStyle: '',
        voiceId: 'zhitian_emo',
        voiceSettings: ''
=======
        languageStyle: ''
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426
      };
    };

    // 创建新角色
    const createCharacter = async () => {
      try {
        const response = await axios.post('/api/characters', newCharacter.value);
        characters.value.push(response.data);
        closeDialog();
      } catch (error) {
        console.error('创建角色失败:', error);
      }
    };

    // 选择角色
    const selectCharacter = async (character) => {
      currentCharacter.value = character;
      try {
        // 获取该角色的所有对话
        const conversationsResponse = await axios.get('/api/character-chat/conversations', {
          params: {
            characterId: character.characterId
          }
        });
        conversations.value = conversationsResponse.data.content;
        
        // 如果有对话，选择最新的一个
        if (conversations.value.length > 0) {
          await switchConversation(conversations.value[0]);
        } else {
          // 如果没有对话，创建新对话
          await createNewConversation(character);
        }
      } catch (error) {
        console.error('获取对话列表失败:', error);
      }
    };

    // 创建新对话
    const createNewConversation = async (character) => {
      try {
        const createResponse = await axios.post('/api/character-chat/conversations', null, {
          params: {
            characterId: character.characterId,
            title: `与${character.name}的对话`
          }
        });
        currentConversation.value = createResponse.data;
        conversations.value.unshift(currentConversation.value);
        currentMessages.value = [];
        scrollToBottom();
      } catch (error) {
        console.error('创建对话失败:', error);
      }
    };

    // 切换对话
    const switchConversation = async (conversation) => {
      currentConversation.value = conversation;
      try {
        const response = await axios.get(`/api/character-chat/conversations/${conversation.characterConversationId}`);
        currentMessages.value = response.data.messages || [];
        scrollToBottom();
      } catch (error) {
        console.error('获取消息失败:', error);
      }
    };

    // 确认删除对话
    const confirmDelete = async (conversation) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这个对话吗？删除后无法恢复。',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        await deleteConversation(conversation);
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + (error.response?.data?.message || '未知错误'));
        }
      }
    };

    // 删除对话
    const deleteConversation = async (conversation) => {
      try {
        await axios.delete(`/api/character-chat/conversations/${conversation.characterConversationId}`);
        conversations.value = conversations.value.filter(
          item => item.characterConversationId !== conversation.characterConversationId
        );
        ElMessage.success('删除成功');
        
        // 如果删除的是当前对话，切换到列表中的第一个对话或创建新对话
        if (currentConversation.value?.characterConversationId === conversation.characterConversationId) {
          if (conversations.value.length > 0) {
            await switchConversation(conversations.value[0]);
          } else {
            await createNewConversation(currentCharacter.value);
          }
        }
      } catch (error) {
        throw error;
      }
    };

    // 确认删除角色
    const confirmDeleteCharacter = async (character) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这个角色吗？删除后该角色的所有对话也将被删除，且无法恢复。',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        await deleteCharacter(character);
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + (error.response?.data?.message || '未知错误'));
        }
      }
    };

    // 删除角色
    const deleteCharacter = async (character) => {
      try {
        await axios.delete(`/api/characters/${character.characterId}`);
        characters.value = characters.value.filter(
          item => item.characterId !== character.characterId
        );
        ElMessage.success('删除成功');
        
        // 如果删除的是当前角色，清空当前状态
        if (currentCharacter.value?.characterId === character.characterId) {
          currentCharacter.value = null;
          currentConversation.value = null;
          conversations.value = [];
          currentMessages.value = [];
        }
      } catch (error) {
        throw error;
      }
    };

    // 发送消息
    const sendMessage = async () => {
      if (!inputMessage.value.trim() || !currentCharacter.value) return;

      const message = {
        content: inputMessage.value,
        senderType: 'user'
      };

      currentMessages.value.push(message);
      inputMessage.value = '';
      scrollToBottom();

      try {
        const response = await axios.post('/api/character-chat/send', {
          characterId: currentCharacter.value.characterId,
          message: message.content,
          conversationId: currentConversation.value?.characterConversationId
        });
        currentMessages.value.push({
          content: response.data.message,
          senderType: 'character'
        });
        scrollToBottom();
      } catch (error) {
        console.error('发送消息失败:', error);
        // 移除之前添加的用户消息
        currentMessages.value.pop();
      }
    };

    // 滚动到底部
    const scrollToBottom = () => {
      setTimeout(() => {
        if (messageList.value) {
          messageList.value.scrollTop = messageList.value.scrollHeight;
        }
      }, 100);
    };

    // 加载角色列表
    onMounted(async () => {
      try {
        const response = await axios.get('/api/characters');
        characters.value = response.data;
      } catch (error) {
        console.error('获取角色列表失败:', error);
      }
    });

    return {
      characters,
      currentCharacter,
      currentConversation,
      conversations,
      currentMessages,
      inputMessage,
      messageList,
      showDialog,
      newCharacter,
      goBack,
      showCreateCharacterDialog,
      closeDialog,
      createCharacter,
      selectCharacter,
      switchConversation,
      confirmDelete,
      confirmDeleteCharacter,
      sendMessage
    };
  }
};
</script>

<style scoped>
.character-chat-container {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
}

.sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.back-btn,
.new-character-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.back-btn {
  background-color: #f0f0f0;
  color: #333;
}

.new-character-btn {
  background-color: #409EFF;
  color: white;
}

.list-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #333;
}

.character-list,
.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.character-item,
.conversation-item {
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
}

.character-item:hover,
.conversation-item:hover {
  background-color: #f5f7fa;
}

.character-item.active,
.conversation-item.active {
  background-color: #ecf5ff;
}

.character-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.character-desc {
  font-size: 12px;
  color: #666;
}

.conversation-title {
  font-size: 14px;
  color: #333;
}

.delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.character-info {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.character-info h2 {
  margin: 0 0 10px;
}

.character-info p {
  margin: 0;
  color: #666;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 20px;
  display: flex;
  width: 100%;
}

.message.user {
  justify-content: flex-end;
}

.message.character {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  word-break: break-word;
  white-space: pre-wrap;
}

.user .message-content {
  background-color: #95EC69;
  color: #000;
}

.character .message-content {
  background-color: white;
  color: #000;
  border: 1px solid #E4E4E4;
}

.input-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  gap: 10px;
}

.input-area textarea {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  resize: none;
}

.send-btn {
  padding: 0 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.send-btn:hover {
  background-color: #66b1ff;
}

.no-character {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.prompt {
  text-align: center;
}

.prompt i {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}

.create-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
<<<<<<< HEAD
  max-height: 80vh;
  overflow-y: auto;
=======
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f0f0f0;
  border: none;
  color: #333;
}

.confirm-btn {
  background-color: #409EFF;
  border: none;
  color: white;
}

.character-item .delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
}

.character-item:hover .delete-btn {
  opacity: 1;
}
</style> 